import Taro, {Component, Config} from '@tarojs/taro'
import {View, Text, Image} from '@tarojs/components'
import NavbarBlock from "../../common/components/navbarBlock";
import classNames from 'classnames'
import './index.scss'

import bg from '../../common/assets/navbar_bg4@2x.png'
import homeCurrentseasonSel from '../../common/assets/home_Currentseason_sel@2x.png'
import homeNextmonthSel from '../../common/assets/home_nextmonth_sel@2x.png'
import homeAllSel from '../../common/assets/home_all_sel@2x.png'
import homeCurrentseasonNor from '../../common/assets/home_Currentseason_nor@2x.png'
import homeNextmonthNor from '../../common/assets/home_nextmonth_nor@2x.png'
import homeAllNor from '../../common/assets/home_all_nor@2x.png'
import common from "../../common/js/common";
import ajax from "../../net/ajax";
import apiObject from "../../net/api";
import BottomLoading from "../../common/components/bottomLoading";


interface ComponentState {
    currentCheck: number
    productList: Array<any>
    scollBbsTop: number
    isShow: boolean,
    level: number,
    pageNo: number,
    pageSize: number,
    tabInfo: any,
    totalPage: number
}

export default class Index extends Component<{}, ComponentState> {

    config: Config = {
        navigationStyle: 'custom',
        navigationBarTitleText: '首页',
        enablePullDownRefresh: true,
        onReachBottomDistance: 50,
        backgroundTextStyle: 'dark',
    };

    constructor(props) {
        super(props);
        this.state = {
            currentCheck: 0,
            productList: [],
            isShow: false,
            scollBbsTop: 100,
            level: 0,
            pageNo: 0,
            pageSize: 10,
            tabInfo: {},
            totalPage: 0
        };
    }

    onShareAppMessage() {
        return {
          title: '抱果精选',
          success(res) {
          }
        }
    }


    componentWillMount() {
        const that = this;
        const {pageSize} = that.state;
        that.initUserInfo().then(() => {
            Taro.showLoading({title: '加载中...'});
            that.fetchSku(0, pageSize, 0);
        });
        Taro.getSystemInfo({
            success: function (res) {
                that.setState({scollBbsTop: res.statusBarHeight + 44});
            }
        })
    }


    async initUserInfo() {
        let userInfo = common.getUserInfo();
        // Taro.getUserProfile();
        if (!userInfo) {
            wx.getUserProfile({
                desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
                success: (res) => {
                    console.log("res.userInfo===>",res, res.userInfo,)
                    common.setUserInfo(res.userInfo);
                }
              })
        } else {
            if(!userInfo.openId){
               let openId = await common.getUserOpenId();
               userInfo.openId = openId;
            }
            await common.authLogin(userInfo);
        }
        common.getUserLevel().then(() => {
            this.setState({
                level: common.getLevel()
            })
        })
    }

    fetchSku(pageNo = 0, pageSize = 10, type = 0) {
        let {productList, tabInfo} = this.state;
        const params = {pageNo: pageNo, pageSize: pageSize, type: type};
        ajax.post(apiObject.supplierIndex, params).then(res => {

            if (res.statusCode == 200) {
                const data = res.data.content;
                const totalPage = res.data.totalPage;
                let tmpArry;
                if (pageNo === 0) {
                    tmpArry = data;
                } else {
                    tmpArry = productList.concat(data);
                }
                tabInfo[type] = {
                    pageNo: pageNo,
                    totalPage: totalPage,
                    productList: tmpArry
                }
                this.setState({
                    productList: tmpArry,
                    tabInfo: tabInfo,
                    totalPage: totalPage
                }, () => {
                    Taro.hideLoading();
                })
            } else {
                //请求异常
                Taro.showToast({
                    title: '请求异常,请重试!',
                    icon: 'none',
                    duration: 2000
                })
            }

        });
    }

    componentDidMount() {

    }


    onTopTabClick(position) {
        console.log('onTopTabClick====',position)
        const {pageSize, tabInfo} = this.state;
        let tmpPageNo = 0;
        let tmpProductList = [];
        let tmpTotalPage = 0;
        if (tabInfo[position]) {
            tmpPageNo = tabInfo[position].pageNo;
            tmpProductList = tabInfo[position].productList;
            tmpTotalPage = tabInfo[position].totalPage;
        }
        this.setState({
            currentCheck: position,
            productList: tmpProductList,
            pageNo: tmpPageNo,
            totalPage: tmpTotalPage
        }, () => {
            if (tmpPageNo === 0) {
                Taro.showLoading({title: '加载中...'});
                this.fetchSku(tmpPageNo, pageSize, position);
            }
        });
    }

    onPageScroll(e) {
        let {scollBbsTop} = this.state;
        this.setState({
            isShow: (e.scrollTop > scollBbsTop) ? true : false
        })
    }

    onPullDownRefresh() {
        let {pageSize,currentCheck} = this.state;
        Taro.showLoading({title: '加载中...'});
        this.initUserInfo();
        this.fetchSku(0, pageSize, currentCheck);
        Taro.stopPullDownRefresh();
    }

    onReachBottom() {
        let {pageNo, pageSize, totalPage, currentCheck} = this.state;
        let tmpPageNo = (pageNo + 1);
        if (totalPage >= tmpPageNo) {
            this.setState({
                pageNo: tmpPageNo
            }, () => {
                this.fetchSku(tmpPageNo, pageSize, currentCheck);
            })
        }
    }

    onItemClick(item) {
        const {level} = this.state;
        Taro.navigateTo({url: `/pages/detail/detail?id=${item.id}&level=${level}`})
    }

    render() {
        let {currentCheck,tabInfo, productList, isShow, scollBbsTop, level} = this.state;
        return (
            <View className='index-container'>
                {isShow && <View className='top-tab' style={`margin-top: ${scollBbsTop}px;`}>
                    <View className={classNames('tab-item', currentCheck == 0 && 'tab-item-check')}
                          onClick={this.onTopTabClick.bind(this, 0)}>
                        <Text
                            className={classNames('tab-default-title', currentCheck == 0 && 'tab-check-title')}>当季产品</Text>
                        <View className={classNames('tab-default-line', currentCheck == 0 && 'tab-check-line')}/>
                    </View>
                    <View className={classNames('tab-item', currentCheck == 1 && 'tab-item-check')}
                          onClick={this.onTopTabClick.bind(this, 1)}>
                        <Text
                            className={classNames('tab-default-title', currentCheck == 1 && 'tab-check-title')}>下月上市</Text>
                        <View className={classNames('tab-default-line', currentCheck == 1 && 'tab-check-line')}/>
                    </View>
                    <View className={classNames('tab-item', currentCheck == 2 && 'tab-item-check')}
                          onClick={this.onTopTabClick.bind(this, 2)}>
                        <Text
                            className={classNames('tab-default-title', currentCheck == 2 && 'tab-check-title')}>所有产品</Text>
                        <View className={classNames('tab-default-line', currentCheck == 2 && 'tab-check-line')}/>
                    </View>
                </View>}
                <NavbarBlock title={'时价查价'}>
                    <Image className='top-bg' mode='widthFix' src={bg}/>
                    <View className='top-tab-content'>
                        <View className={classNames('tab-item', currentCheck == 0 && 'tab-item-check')} onClick={this.onTopTabClick.bind(this, 0)}>
                            <Image className='item-img' mode='widthFix'
                                   src={currentCheck == 0 ? homeCurrentseasonSel : homeCurrentseasonNor}/>
                        </View>
                        <View className={classNames('tab-item', currentCheck == 1 && 'tab-item-check')} onClick={this.onTopTabClick.bind(this, 1)}>
                            <Image className='item-img' mode='widthFix'

                                   src={currentCheck == 1 ? homeNextmonthSel : homeNextmonthNor}/>
                        </View>
                        <View className={classNames('tab-item', currentCheck == 2 && 'tab-item-check')} onClick={this.onTopTabClick.bind(this, 2)}>
                            <Image className='item-img' mode='widthFix'
                                   src={currentCheck == 2 ? homeAllSel : homeAllNor}/>
                        </View>
                    </View>
                    {productList && productList.map((item, index) => (
                        <View className='list-item' key={'productList' + index}
                              onClick={this.onItemClick.bind(this, item)}>
                            <Image
                                className='list-img'
                                mode='aspectFill'
                                src={item.skuImg}/>
                            <View className='list-bottom'>
                                <View className='title-content'>
                                    <Text className='title'>{item.name}</Text>
                                    <Text className='code'>{item.spac}</Text>
                                </View>
                                <View className='des-content'>
                                    <Text className='price-title'>供货价</Text>
                                    {level === 0 && <Text
                                        className='price'>¥{item.sourcePrice > 0 ? parseFloat((item.sourcePrice / 100).toFixed(2)) : '***'}</Text>}
                                    {level === 1 && <Text
                                        className='price'>¥{item.firstSourcePrice > 0 ? parseFloat((item.firstSourcePrice / 100).toFixed(2)) : item.firstSourcePrice}</Text>}
                                    {level === 2 && <Text
                                        className='price'>¥{item.secondSourcePrice > 0 ? parseFloat((item.secondSourcePrice / 100).toFixed(2)) : item.secondSourcePrice}</Text>}
                                    {level === 3 && <Text
                                        className='price'>¥{item.thridSourcePrice > 0 ? parseFloat((item.thridSourcePrice / 100).toFixed(2)) : item.thridSourcePrice}</Text>}
                                    {level === 4 && <Text
                                        className='price'>¥{item.sourcePrice > 0 ? parseFloat((item.sourcePrice / 100).toFixed(2)) : item.sourcePrice}</Text>}

                                    <Text className='price-title'>建议售价</Text>
                                    {level === 0 && <Text
                                        className='price'>¥{item.salePrice > 0 ? parseFloat((item.salePrice / 100).toFixed(2)) : '***'}</Text>}
                                    {level === 1 && <Text
                                        className='price'>¥{item.firstSalePrice > 0 ? parseFloat((item.firstSalePrice / 100).toFixed(2)) : item.firstSalePrice}</Text>}
                                    {level === 2 && <Text
                                        className='price'>¥{item.secondSalePrice > 0 ? parseFloat((item.secondSalePrice / 100).toFixed(2)) : item.secondSalePrice}</Text>}
                                    {level === 3 && <Text
                                        className='price'>¥{item.thridSalePrice > 0 ? parseFloat((item.thridSalePrice / 100).toFixed(2)) : item.thridSalePrice}</Text>}
                                    {level === 4 && <Text
                                        className='price'>¥{item.salePrice > 0 ? parseFloat((item.salePrice / 100).toFixed(2)) : item.salePrice}</Text>}
                                    <View className='empty'/>
                                    <Text className='show-history'>查看历史价格</Text>
                                </View>
                            </View>
                        </View>
                    ))}
                </NavbarBlock>
                <BottomLoading
                    list={productList}
                    totalPage={tabInfo[currentCheck] && tabInfo[currentCheck].totalPage}
                    pageNo={tabInfo[currentCheck] && tabInfo[currentCheck].pageNo}
                    isShowLookBtn={false}
                />
            </View>
        )
    }
}
